package com.zhou.test.config;

import com.zhou.test.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
class SessionHandlerInterceptor extends HandlerInterceptorAdapter {
    // 在调用 Controller 方法前会调用此方法 。
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            // 没有登录,重定向 login.html
            response.sendRedirect("/login.html");
            return false;
        }
        return true;
    }

    // 在调用 Controller 方法结束后、页面渲染之前调用此方法，比如可以在这里将渲染的视图名称更改为其他视图名称
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //页 面渲染完毕后调用此方法，通常用来清除某些资源，类似 Java 语法的 finally

    }

    //  页面渲染完毕后调用此方法 。
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}